import { getMoment } from '@/services/api';
import { formatDate } from '@/utils';
import { ProList } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { Button, Input } from 'antd';
import { useEffect, useState } from 'react';
import './index.css';
import { addComment } from '@/services/api/comment';

export default function MomentDetail() {
  const { id } = useParams();

  const [moment, setMoment] = useState({});
  const [content, setContent] = useState('');


  function getMomentData() {
    try {
      getMoment(id as string).then((res) => {
        console.log(res.data, '动态详情');
        setMoment(res.data);
      });
    } catch (error) {
      console.log(error.message);
      
    }
  }

  // 通过id获取动态详情
  useEffect(() => {
    getMomentData()
  }, [id]);


  // 发表评论
  async function handleComment() {
    const params = {
      momentId: id,
      content
    }
    console.log(params);
    await addComment(params)
    setContent('') // 清空输入框
    getMomentData()
    
  }

  return (
    <div className="moment-detail">
      <div className="moment-detail-header">
        {/* <img src={moment.user_avatar} alt="" /> */}
        <h2>{moment.content}</h2>
        <p>
          作者：<span>{moment.user_name}</span>
          发布于：{formatDate(moment.createAt)}
        </p>
      </div>

      <div className="moment-detail-content">
        <Button className='plBtn' onClick={handleComment}>评论</Button>
        <Input.TextArea
          rows={3}
          placeholder="欢迎分享你的想法！请留下你的评论~"
          value={content}
          showCount
          maxLength={300}
          style={{
            height: 120,
            resize: 'none',
          }}
          onChange={(e) => setContent(e.target.value)}
        />
        <ProList
          rowKey="id"
          dataSource={moment.comments}
          showActions="hover"
          metas={{
            title: {
              render: (_, { user }) => <span>{user.username}</span>,
            },
            avatar: {
              render: (_, { user }) => (
                <img
                  style={{borderRadius: '50%'}}
                  width={40}
                  height={40}
                  src={
                    user.avatar_url ||
                    'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
                  }
                />
              ),
            },
            description: {
              dataIndex: 'content',
            },
          }}
        />
      </div>
    </div>
  );
}
